//
// Created by wll on 2022/2/8.
//

#include "CommandLineParameters.h"
#include <sstream>
#include "WllString.h"
using namespace std;
using namespace Wll::Util;

CommandLineParameters::CommandLineParameters(int argc, char** argv)
{
    int mode = 0;
    string key = "";
    for(int i=1; i<argc; i++)
    {
        string parameter = argv[i];
        if (parameter.substr(0,2) == "--")
        {
            mode = 1;
            key = parameter.substr(2,string::npos);
            options[key] = "";
        }
        else
        {
            if (mode == 1)
            {
                options[key] = parameter;
            }
            else
            {
                args.push_back(parameter);
            }
            mode = 0;
        }
    }
}

CommandLineParameters::CommandLineParameters(const std::string& command_line)
{
    vector<string> fields;
    split(command_line, ' ', fields);

    int mode = 0;
    string key = "";
    for(int i=0; i<fields.size(); i++)
    {
        string parameter = fields[i];
        if (parameter == "") continue;

        if (parameter.substr(0,2) == "--")
        {
            mode = 1;
            key = parameter.substr(2,string::npos);
            options[key] = "";
        }
        else
        {
            if (mode == 1)
            {
                options[key] = parameter;
            }
            else
            {
                args.push_back(parameter);
            }
            mode = 0;
        }
    }
}

std::string CommandLineParameters::GetOption(const std::string& key)
{
    map<string,string>::iterator i = options.find(key);
    if (i != options.end())
    {
        return i->second;
    }
    else
    {
        return "";
    }
}

std::string CommandLineParameters::GetParameter(int i)
{
    if (0 <= i && i < args.size())
    {
        return args[i];
    }
    else
    {
        return "";
    }
}

std::vector<std::string>& CommandLineParameters::GetParameters()
{
    return args;
}

std::string CommandLineParameters::ToString()
{
    stringstream ss;
    for (map<string,string>::iterator i = options.begin(); i != options.end(); ++i)
    {
        ss << "--" << i->first << " " << i->second << " ";
    }
    for (vector<string>::iterator i = args.begin(); i != args.end(); ++i)
    {
        ss << *i << " ";
    }
    return ss.str();
}